package ddd.ajava.chapter5.question1.udp;
import java.net.*;
import java.util.*;
import java.io.*;

public class UdpFileServer {
	public static void main(String[] args) {  
		
		try {  
			
			InetAddress ip = InetAddress.getLocalHost();  
			int port = 8888;  
			int port2 =8889;
			
            // 创建接收方的套接字,并制定端口号和IP地址  
			DatagramSocket getSocket = new DatagramSocket(port, ip); 	//得到发往这个端口的数据包
			DatagramSocket getSocket1 = new DatagramSocket(port2, ip);  //得到文件名数据
			//*得到文件名
			byte[] buffer1 = new byte[4033];
			DatagramPacket getPacket1 = new DatagramPacket(buffer1, buffer1.length);  // 通过套接字接收文件名数据  
			getSocket1.receive(getPacket1); //收到发送端发送来的文件名数据报
			String fileName = new String(buffer1, 0, getPacket1.getLength());//具体名字	
			//*得到文件名
			
			System.out.println(fileName+"\n");
//			File file=new File("uploadUdp",fileName);
			File file=new File(fileName);
			PrintWriter write=new PrintWriter(file);//写入一个文件
			
			byte[] buffer = new byte[4033];  // 把得到的数据报放入这个缓冲区
			DatagramPacket getPacket = new DatagramPacket(buffer, buffer.length);  // 通过套接字接收数据  
			getSocket.receive(getPacket); //收到发送端发送来的数据报
			String getMes = new String(buffer, 0, getPacket.getLength());//具体信息 		
			write.print(getMes);
			
			// 通过数据报得到发送方的套接字地址  
			SocketAddress sendAddress = getPacket.getSocketAddress();  
			String feedback = "我收到了！";  //确认消息
			byte[] backBuf = feedback.getBytes();  
			DatagramPacket sendPacket = new DatagramPacket(backBuf, backBuf.length, sendAddress);  
			getSocket.send(sendPacket);  
			getSocket.close();  
			write.close();
		 } catch (Exception e) {  
			 e.printStackTrace();  
        } 
    }
} 
